package com.example.travel.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.travel.domain.entity.User;
import com.example.travel.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author : LinQingLiang
 * @file : TokenUtils.java
 * @Since : 2023/1/24 20:38
 */
@Component
public class TokenUtils {

    private static UserService staticUserService;

    @Resource
    private UserService userService;

    @PostConstruct
    public void setUserService(){
        staticUserService = userService;
    }

    /**
     * 生成  Token
     * @param userId
     * @param sign
     * @return
     */
    //jwt有三部分分别是：头部、载荷、签证
    public static String getToken(String userId,String sign) {
        String token = JWT.create().withAudience(userId) // 将user  id 保存到token  作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2000))   //2000小时过期
                .sign(Algorithm.HMAC256(sign));  //以password 作为 token密匙
        return token;
    }

    /**
     * 获取当前用户信息
     * @return user对象
     */
    public static User getUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Authorization");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(Integer.valueOf(userId));
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }
}
